<?php
//	echo "\n\nUsage : /usr/local/php5/bin/php makedirs.php Alphabetical .\n\n";

	$folder = opendir($argv[1]);
	$destdr = $argv[1]."../";
	
	$temp = explode("/",$argv[1]);
	$basedirname = $temp[count($temp)-2];
	
	$genres	= array();
	$years	= array();
	$rates	= array();
	
	while(false !== ($file = readdir($folder))){
		if(substr($file, 0, 1) == "."){ continue; }
		$tmp = scandir($argv[1]."/".$file);
		foreach($tmp as $df){
			if(strpos($df, "xml") > 1){
				$dom = new DomDocument();
				$dom->load($argv[1]."/".$file."/".$df);
				$mygenres = $dom->getElementsByTagName("genre");
				foreach($mygenres as $genre){
					$gen = $genre->textContent;
					$gen = str_replace("IMDb ","",$gen);
					$gen = str_replace(" section","",$gen);
					if(!isset($genres[$gen])){ $genres[$gen] = array(); }
					array_push($genres[$gen], $file);
				}
				$myyear = $dom->getElementsByTagName("published");
				foreach($myyear as $myear){
					$myear = substr($myear->textContent,0,4);
					if(!isset($years[$myear])){ $years[$myear] = array(); }
					array_push($years[$myear], $file);
				}
				$myrating = $dom->getElementsByTagName("imdbRating");
				foreach($myrating as $rating){
					$rat = substr($rating->textContent,0,1);
					if(!isset($rates[$rat])){ $rates[$rat] = array(); }
					array_push($rates[$rat], $file);
				}
				continue;
			}
		}
	}
	
	
	if(!file_exists($destdr."/By Genre")){ 
		if(mkdir($destdr."/By Genre") !== false){ ; }
	}
	if(!file_exists($destdr."/By Year")){ mkdir($destdr."/By Year"); }
	if(!file_exists($destdr."/By Rating")){ mkdir($destdr."/By Rating"); }

	foreach($genres as $genre=>$movies){
		if(!file_exists($destdr."/By Genre/".$genre)){ mkdir($destdr."/By Genre/".$genre); }
		foreach($movies as $movie){
			if(!file_exists($destdr."/By Genre/".$genre."/".$movie)){
				symlink("../../".$basedirname."/".$movie, $destdr."/By Genre/".$genre."/".$movie);
			}
		}
	}
	foreach($years as $year=>$movies){
		if(!file_exists($destdr."/By Year/".$year)){ mkdir($destdr."/By Year/".$year); }
		foreach($movies as $movie){
			if(!file_exists($destdr."/By Year/".$year."/".$movie)){
				symlink("../../".$basedirname."/".$movie, $destdr."/By Year/".$year."/".$movie);
			}
		}
	}
	foreach($rates as $rate=>$movies){
		if(!file_exists($destdr."/By Rating/".$rate)){ mkdir($destdr."/By Rating/".$rate); }
		foreach($movies as $movie){
			if(!file_exists($destdr."/By Rating/".$rate."/".$movie)){
				symlink("../../".$basedirname."/".$movie, $destdr."/By Rating/".$rate."/".$movie);
			}
		}
	}


/*
	function scandir($dir){
		$tmp = array();
		$dir = opendir($dir);
		while(false !== ($file = readdir($dir))){
			if(substr($file, 0, 1) != "."){
				array_push($tmp, $file);
			}
		}
		print_r($tmp);
		return($tmp);
	}
*/
?>